//
//  HREnterInvitationCodeViewController.m
//  Hear
//
//  Created by mac on 2017/7/25.
//  Copyright © 2017年 mac. All rights reserved.
// 邀请码

#import "HREnterInvitationCodeViewController.h"
#import "HREnterTextFiledView.h"
#import "HRUpdataUserInfoModel.h"
#import "HRContactsManager.h"
#import "YContactObject.h"
#import "HRLocationViewModel.h"
#import "HRRecordAudioViewController.h"

@interface HREnterInvitationCodeViewController ()
@property (nonatomic, strong)HREnterTextFiledView *codeTextFiledView;
@property (nonatomic, strong) HRContactsManager * contactManager;
@property (nonatomic, strong)HRLocationViewModel *locationViewModel;

@end

@implementation HREnterInvitationCodeViewController

#pragma mark - Get and Set
- (HRLocationViewModel *)locationViewModel{
    if (_locationViewModel == nil) {
        _locationViewModel = [[HRLocationViewModel alloc] init];
    }
    return _locationViewModel;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"输入邀请码";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupView];
    
    self.contactManager = [HRContactsManager shareInstance];

    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"hasRecodeSound"];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"redRemendOfCicle"];

}

- (void)setupView{
    UIButton *leftButton = [UIButton buttonWithType:0];
    leftButton.size = CGSizeMake(20, 20);
    [leftButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    
    
    
    UIButton *rightButton = [UIButton buttonWithType:0];
    rightButton.size = CGSizeMake(40, 30);
    [rightButton setTitle:@"跳过" forState:0];
    [rightButton addTarget:self action:@selector(rightButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    
    self.codeTextFiledView = [HREnterTextFiledView new];
    [self.view addSubview:self.codeTextFiledView];
    self.codeTextFiledView.textField.placeholder = @"请复制你的邀请码";
    [self.codeTextFiledView.textField setValue:CustomColor(160, 160, 160, 1) forKeyPath:@"_placeholderLabel.textColor"];
    self.codeTextFiledView.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTextFiledView.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.codeTextFiledView.textField.textColor = CustomColor(160, 160, 160, 1);
    self.codeTextFiledView.leftImageView.image = [UIImage imageNamed:@"邀请码"];

    
    UIButton *nextButton = [UIButton buttonWithType:0];
    nextButton.layer.cornerRadius = 8;
    nextButton.clipsToBounds = YES;
    [nextButton setTitle:@"确定" forState:0];
    [nextButton setTitleColor:[UIColor whiteColor] forState:0];
    nextButton.titleLabel.font = CustomUIFont(15);
    [nextButton addTarget:self action:@selector(nextButtonClick) forControlEvents:UIControlEventTouchUpInside];
    nextButton.backgroundColor = MainColor;
    [self.view addSubview:nextButton];
    
    WeakSelf
    [self.codeTextFiledView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.right.equalTo(weakSelf.view).offset(-20);
        make.top.equalTo(weakSelf.view).offset(100);
        make.height.equalTo(@45);
    }];
    
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@40);
        make.right.equalTo(weakSelf.view).offset(-40);
        make.top.equalTo(weakSelf.codeTextFiledView.mas_bottom).offset(80);
        make.height.equalTo(@40);
    }];
    
    
}

- (void)rightButtonClick{
    [self loginEaseMob];
    [self.navigationController removeFromParentViewController];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window removeAllSubviews];
    window = nil;
    [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];
    
}


- (void)nextButtonClick{
    
    
    if (self.codeTextFiledView.textField.text.length < 6){
        [MBProgressHUD showMessage:@"邀请码格式不正确" finishBlock:nil];
        return;
    }
    WeakSelf
    
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"CurrentUserLocalId"] = USERID;
    paramDict[@"UserNo"] = self.codeTextFiledView.textField.text;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    
    YTKApi *api = [YTKApi apiPostWithUrl:@"UserInfo/Post_SaveUserInvitationCode" para:paramDict];
    [api getSuccessToken:^() {
        [api setRequestSerializerType:YTKRequestSerializerTypeHTTP];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            DDLog(@"");
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf loginEaseMob];
                [weakSelf.navigationController removeFromParentViewController];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                [window removeAllSubviews];
                window = nil;
                [UIApplication sharedApplication].keyWindow.rootViewController = [[HRTabBarViewController alloc] init];
            });
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}


- (void)loginEaseMob
{
    [self getAddressBookList];

    WeakSelf
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        HRUpdataUserInfoModel *infoModel = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
        EMError *error = [[EMClient sharedClient] loginWithUsername:infoModel.LocalId password:infoModel.Password];
        if (!error){
            DDLog(@"登录聊天服务器成功");
            
            [[EMClient sharedClient].options setIsAutoLogin:YES];
            EMPushOptions *options = [[EMClient sharedClient] pushOptions];
            options.displayStyle = EMPushDisplayStyleMessageSummary;
            options.nickname = infoModel.NickName;
            [[EMClient sharedClient] updatePushOptionsToServer];
        }
    });
}


- (void)getAddressBookList{
    WeakSelf
    NSMutableArray *mobileNumArr = [NSMutableArray array];
    [self.contactManager requestContactsComplete:^(NSArray<YContactObject *> * _Nonnull contacts) {
        
        //开始赋值
        for (YContactObject *object in contacts) {
            YContactPhoneObject *phontObject = [object.phoneObject firstObject];
            NSString *mobileNumStr = [phontObject.phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
            if ([mobileNumStr isMobileNumber]){
                DDLog(@"phoneNumber========================%@",mobileNumStr);
                [mobileNumArr addObject:mobileNumStr];
            }
            
        }
        [weakSelf postSaveUserContacts:[mobileNumArr jsonStringEncoded]];
    }];
}

- (void)postSaveUserContacts:(NSString *)MobileList{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"MobileList"] = MobileList;
    paramDict[@"CreateTime"] = [self getCurrentTime];
    [self.locationViewModel postSaveUserContacts:paramDict isSeccess:^(BOOL isSeccess) {
        
    }];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:NO];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }

}


- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
